//
//  BeautyInViewController.m
//  ForYourBeauty
//
//  Created by Kelly xu on 2019/5/31.
//  Copyright © 2019 changrenTech. All rights reserved.
//

#import "BeautyInViewController.h"
#import "TYWaveProgressView.h"
#import "UploadRecordViewController.h"
#import "DeviceViewModel.h"
#import "DeviceListViewController.h"
#import "MyDeviceListViewController.h"
#import "ZYSuspensionView.h"
#import "GMWKWebViewController.h"
#import "ImagePickerManager.h"
#import "CountDownUtils.h"
@interface BeautyInViewController ()<ZYSuspensionViewDelegate>{
    
}
@property (nonatomic, weak) TYWaveProgressView *waveProgressView1;
@property (nonatomic, strong) DeviceViewModel *deviceViewModel;
@property (nonatomic, weak)IBOutlet UILabel *deviceName;
@property (nonatomic, weak)IBOutlet UILabel *deviceTime;

@property (nonatomic, weak)IBOutlet UIButton *pauseBtn;
@property (nonatomic, weak)IBOutlet UILabel *pauseLab;
@property (nonatomic, weak)IBOutlet UIButton *startBtn;
@property (nonatomic, weak)IBOutlet UILabel *startLab;
@property (nonatomic, weak)IBOutlet UIButton *closeBtn;
@property (nonatomic, weak)IBOutlet UILabel *closeLab;
@property (nonatomic, weak)IBOutlet UIButton *continueBtn;
@property (nonatomic, weak)IBOutlet UILabel *continueLab;

@property (nonatomic, strong) TYWaveProgressView *waveProgressView;
@property(nonatomic,strong)dispatch_source_t countDownTimer;
@property(nonatomic,assign)BOOL hasTimer;
@property(nonatomic,strong)ZYSuspensionView *sus2;
@property(nonatomic,assign)BOOL isStart;
@property(nonatomic,assign)BOOL isSuspend;
@property(nonatomic,strong)DeviceContinueModel *continueModel;
@property(nonatomic,assign)BOOL isRequest;
@property(nonatomic,assign)NSInteger runTimeForCountDown;
@end

@implementation BeautyInViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationController.navigationBarHidden = NO;
    self.navigationItem.title = @"美光中";
    [self setNavRightBtnForImage:[UIImage imageNamed:@"paizhao"]];
    [self startBtnShow];
    [self.sus2 show];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(cancelTimeCounter) name:@"cancleTimeCounter" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(callUpTimeCounter) name:@"callUpTimeCounter" object:nil];
}
-(void)cancelTimeCounter{
    [self stopCountDownTimer];
}
-(void)callUpTimeCounter{
    [self.deviceViewModel getDeviceRemainTime:[NSString stringWithFormat:@"%.0f",self.deviceModel.internalBaseClassIdentifier] cmp:^(DeviceContinueModel * _Nonnull model) {
        NSString *powerCountStr = [NSString stringWithFormat:@"%.0f",model.prowerNumber];
        [self reloadWaveProgressView:powerCountStr];
        if (!model.isOnlie) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"设备已离线" preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self stopCountDownTimer];
                [self.rt_navigationController popViewControllerAnimated:YES];
            }]];
            [self presentViewController:alert animated:YES completion:nil];
        }else{
            self.hasTimer = NO;
            NSInteger minutes = model.lastTime/60;
            NSInteger sec = model.lastTime - minutes*60;
            NSString *strTime = [NSString stringWithFormat:@"%02ld:%02ld",minutes,sec];
            self.waveProgressView.numberLabel.text = strTime;
            switch ([model.status integerValue]) {
                case 2://开始状态
                {
                    self.runTimeForCountDown = model.lastTime;
                    self.pauseBtn.hidden = NO;
                    self.pauseLab.hidden = NO;
                    self.closeBtn.hidden = NO;
                    self.closeLab.hidden = NO;
                    self.startBtn.hidden = YES;
                    self.startLab.hidden = YES;
                    self.continueBtn.hidden = YES;
                    self.continueLab.hidden = YES;
                    NSInteger leftSecs = model.lastTime;
                    [self startOrContinueTimer:leftSecs];
                }
                    break;
                case 1://暂停状态
                {
                    self.runTimeForCountDown = model.lastTime;
                    [self pauseBtnPressed];
                }
                    break;
                case 3://闲置状态
                {
                    [self startBtnShow];
                }
                    break;
                default:
                    break;
            }
        }
    }];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    if (self.isRequest == NO) {
        [self.deviceViewModel getLastDeviceUseTime:^(NSInteger time) {
            self.deviceTime.text = [NSString stringWithFormat:@"%ld分钟",time/60];
        }];
        [self.deviceViewModel fetchDeviceInfo:[NSString stringWithFormat:@"%.0f",self.deviceModel.internalBaseClassIdentifier]  cmp:^(NSDictionary * _Nonnull deviceInfo) {
            if ([deviceInfo isKindOfClass:[NSDictionary class]]) {
                if ([[deviceInfo objectForKey:@"online"] boolValue]) {
                    [self setupWaterWave:deviceInfo];
                    NSString *minutes = [self.deviceTime.text stringByReplacingOccurrencesOfString:@"分钟" withString:@""];
                    self.runTimeForCountDown = [minutes integerValue]*60;
                    [self callUpTimeCounter];
                }else{
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"设备已离线" preferredStyle:UIAlertControllerStyleAlert];
                    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        [self.rt_navigationController popViewControllerAnimated:YES];
                    }]];
                    [self presentViewController:alert animated:YES completion:nil];
                }
            }
        }];
        self.isRequest = YES;
    }
    
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:YES];
}
//开始
-(IBAction)startBtnPressed:(id)sender{
//    NSString *minutes = [self.deviceTime.text stringByReplacingOccurrencesOfString:@"分钟" withString:@""];
    [self.deviceViewModel optionDevice:[NSString stringWithFormat:@"%.0f",self.deviceModel.internalBaseClassIdentifier] option:@"1" runtime:self.runTimeForCountDown  suc:^{
        self.isStart = YES;
        [self otherTwoBtnsShow];
    } fail:^{
        
    }];
}
//继续
-(IBAction)continueBtnPressed:(id)sender{
//    NSString *minutes = [self.deviceTime.text stringByReplacingOccurrencesOfString:@"分钟" withString:@""];
    [self.deviceViewModel optionDevice:[NSString stringWithFormat:@"%.0f",self.deviceModel.internalBaseClassIdentifier] option:@"4" runtime:self.runTimeForCountDown suc:^{
        [self otherTwoBtnsShow];
    } fail:^{
        
    }];
}
//暂停
-(IBAction)pauseBtnPressed:(id)sender{
//    NSString *minutes = [self.deviceTime.text stringByReplacingOccurrencesOfString:@"分钟" withString:@""];
    [self.deviceViewModel optionDevice:[NSString stringWithFormat:@"%.0f",self.deviceModel.internalBaseClassIdentifier] option:@"3" runtime:self.runTimeForCountDown suc:^{
        [self suspendCountDownTimer];
        [self pauseBtnPressed];
    } fail:^{
        
    }];
}
//关机
-(IBAction)closeBtnPressed:(id)sender{
//    NSString *minutes = [self.deviceTime.text stringByReplacingOccurrencesOfString:@"分钟" withString:@""];
    [self.deviceViewModel optionDevice:[NSString stringWithFormat:@"%.0f",self.deviceModel.internalBaseClassIdentifier] option:@"2" runtime:self.runTimeForCountDown suc:^{
        self.isStart = NO;
        [self startBtnShow];
        [self stopCountDownTimer];
        [self.sus2 removeFromSuperview];
        UploadRecordViewController *uploadRecord = [[UploadRecordViewController alloc]init];
        [self.rt_navigationController pushViewController:uploadRecord animated:YES complete:nil];
    } fail:^{
        
    }];
}
-(IBAction)goDeviceList:(id)sender{
//    MyDeviceListViewController *deviceList = [[MyDeviceListViewController alloc]init];
//    [self.rt_navigationController pushViewController:deviceList animated:YES complete:nil];
}
-(IBAction)choiceDeviceTime:(id)sender{
    if (!self.isStart) {
        NSArray *array = @[@"5分钟",@"10分钟",@"20分钟",@"30分钟",@"40分钟",@"50分钟"];
        [SMBRadioPickerView showPickerViewWithStrings:array completion:^(NSString *selectedString) {
            self.deviceTime.text = selectedString;
            NSString *minutes = [self.deviceTime.text stringByReplacingOccurrencesOfString:@"分钟" withString:@""];
            self.runTimeForCountDown = [minutes integerValue]*60;
        }];
    }
}
-(void)startBtnShow{
    self.pauseBtn.hidden = YES;
    self.pauseLab.hidden = YES;
    self.closeBtn.hidden = YES;
    self.closeLab.hidden = YES;
    self.startBtn.hidden = NO;
    self.startLab.hidden = NO;
    self.continueBtn.hidden = YES;
    self.continueLab.hidden = YES;
}
-(void)pauseBtnPressed{
    self.pauseBtn.hidden = YES;
    self.pauseLab.hidden = YES;
    self.closeBtn.hidden = NO;
    self.closeLab.hidden = NO;
    self.startBtn.hidden = YES;
    self.startLab.hidden = YES;
    self.continueBtn.hidden = NO;
    self.continueLab.hidden = NO;
}
-(void)otherTwoBtnsShow{
    self.pauseBtn.hidden = NO;
    self.pauseLab.hidden = NO;
    self.closeBtn.hidden = NO;
    self.closeLab.hidden = NO;
    self.startBtn.hidden = YES;
    self.startLab.hidden = YES;
    self.continueBtn.hidden = YES;
    self.continueLab.hidden = YES;
    [self startOrContinueTimer:self.runTimeForCountDown];
}
-(void)setupWaterWave:(NSDictionary*)deviceInfo{
    UIImageView *waveBg = [[UIImageView alloc]initWithFrame:CGRectMake((DEVICE_WIDTH - 234)/2, StatusBarHeight+93, 234, 234)];
    waveBg.layer.cornerRadius = 117;
    waveBg.backgroundColor = [UIColor colorWithRed:244/255.0 green:81/255.0 blue:66/255.0 alpha:1.0];
    [self.view addSubview:waveBg];
    
    [self.view addSubview:self.waveProgressView];
    NSString *powerCountStr = [NSString stringWithFormat:@"%@",[deviceInfo objectForKey:@"powerNum"]];
    [self reloadWaveProgressView:powerCountStr];
    
    UIImageView *roundBg = [[UIImageView alloc]initWithFrame:CGRectMake(waveBg.center.x-290/2, waveBg.center.y-290/2, 290, 290)];
    [roundBg setImage:[UIImage imageNamed:@"roundBg"]];
    [self.view addSubview:roundBg];
    
    self.deviceName.text = [NSString stringWithFormat:@"%@-%@",[deviceInfo objectForKey:@"deviceType"],[deviceInfo objectForKey:@"deviceSn"]];
    self.deviceTime.text = [NSString stringWithFormat:@"30分钟"];
}
-(void)reloadWaveProgressView:(NSString*)powerCountStr{
    if (EC_ISNullStr(powerCountStr)) {
        self.waveProgressView.batteryLabel.text = @"0%";
        self.waveProgressView.percent = 0;
        self.waveProgressView.batteryIcon.image = [UIImage imageNamed:@"0"];
    }else{
        self.waveProgressView.batteryLabel.text = [NSString stringWithFormat:@"%@%%",powerCountStr];
        self.waveProgressView.percent = [powerCountStr floatValue]/100;
        self.waveProgressView.batteryIcon.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@",powerCountStr]];
    }
    [self.waveProgressView startWave];
}
-(void)leftbuttonPressed:(id)sender{
    [self stopCountDownTimer];
    [self.sus2 removeFromSuperview];
    [self.rt_navigationController popViewControllerAnimated:YES complete:nil];
}
-(void)rightbuttonPressed:(id)sender{
    [[ImagePickerManager sharedImgPicker] showCamaraWithCompletion:^(UIImage *usericon, UIImagePickerController *imgPicker) {
        [imgPicker dismissViewControllerAnimated:YES completion:nil];
    }];
}
-(DeviceViewModel*)deviceViewModel{
    if (!_deviceViewModel) {
        _deviceViewModel = [[DeviceViewModel alloc]init];
    }
    return _deviceViewModel;
}
/** 点击悬浮球的回调 */
- (void)suspensionViewClick:(ZYSuspensionView *)suspensionView{
    GMWKWebViewController *webView = [[GMWKWebViewController alloc]init];
    webView.url = @"https://tb.53kf.com/code/app/A67889FD499F556C15F78A820D19647E9/1?device=ios";
    [self.rt_navigationController pushViewController:webView animated:YES complete:nil];
}
#pragma mark - instance
-(TYWaveProgressView*)waveProgressView{
    if (!_waveProgressView) {
        _waveProgressView = [[TYWaveProgressView alloc]initWithFrame:CGRectMake((DEVICE_WIDTH - 234)/2, StatusBarHeight+93, 234, 234)];
        _waveProgressView.waveViewMargin = UIEdgeInsetsMake(0, 0, 0, 0);
    }
    return _waveProgressView;
}
#pragma mark - 倒计时
-(dispatch_source_t)countDownTimer{
    if (!_countDownTimer) {
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        _countDownTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    }
    return _countDownTimer;
}
-(void)startOrContinueTimer:(NSInteger)leftSecs{
    if (!self.hasTimer) {
        self.hasTimer = YES;
        [CountDownUtils timeCounterWithLab:self.waveProgressView.numberLabel leftSecs:leftSecs timer:self.countDownTimer perSecHandle:^{
            [self.deviceViewModel getDeviceRemainTime:[NSString stringWithFormat:@"%.0f",self.deviceModel.internalBaseClassIdentifier] cmp:^(DeviceContinueModel * _Nonnull model) {
                NSString *powerCountStr = [NSString stringWithFormat:@"%.0f",model.prowerNumber];
                [self reloadWaveProgressView:powerCountStr];
                if (!model.isOnlie) {
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"设备已离线" preferredStyle:UIAlertControllerStyleAlert];
                    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        [self stopCountDownTimer];
                        [self.rt_navigationController popViewControllerAnimated:YES];
                    }]];
                    [self presentViewController:alert animated:YES completion:nil];
                }
            }];
        } handle:^{
            [self stopCountDownTimer];
            [self closeBtnPressed:[UIButton buttonWithType:UIButtonTypeCustom]];
        }];
    }else{
        self.isSuspend = NO;
        dispatch_resume(self.countDownTimer);
    }
}
-(void)suspendCountDownTimer{
    self.isSuspend = YES;
    dispatch_suspend(self.countDownTimer);
}
-(void)stopCountDownTimer{
    if (self.isSuspend) {
        dispatch_resume(self.countDownTimer);
        self.isSuspend = NO;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            dispatch_source_cancel(self.countDownTimer);
            self.countDownTimer = nil;
        });
    }else{
        if (_countDownTimer) {
            dispatch_source_cancel(self.countDownTimer);
            self.countDownTimer = nil;
        }
    }
}
-(ZYSuspensionView*)sus2{
    if (!_sus2) {
        _sus2 = [[ZYSuspensionView alloc] initWithFrame:CGRectMake(DEVICE_WIDTH-50, 200, 50, 50)
                                                                   color:[UIColor clearColor]
                                                                delegate:self];
        _sus2.leanType = ZYSuspensionViewLeanTypeEachSide;
        [_sus2 setImage:[UIImage imageNamed:@"icon_kf_float"] forState:UIControlStateNormal];
    }
    return _sus2;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
